package com.example.demo.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.PostConstruct;
import java.io.File;

@Configuration
public class FileUploadConfig implements WebMvcConfigurer {
    
    @Value("${file.upload.path:${user.dir}/uploads}")
    private String uploadPath;
    
    @Value("${file.upload.url-prefix:/uploads/}")
    private String urlPrefix;
    
    @Value("${server.url:http://localhost:8080}")
    private String serverUrl;
    
    // 获取文件上传根路径
    public static String UPLOAD_PATH;
    
    // 获取文件访问路径前缀
    public static String FILE_PREFIX;
    
    // 服务器URL
    public static String SERVER_URL;
    
    @PostConstruct
    public void init() {
        // 初始化静态变量
        UPLOAD_PATH = uploadPath + File.separator;
        FILE_PREFIX = urlPrefix;
        SERVER_URL = serverUrl;
        
        // 创建上传根目录
        createDirectory(UPLOAD_PATH);
        // 创建头像目录
        createDirectory(UPLOAD_PATH + "avatar");
    }
    
    // 创建目录
    private void createDirectory(String path) {
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 配置静态资源映射
        registry.addResourceHandler(urlPrefix + "**")
                .addResourceLocations("file:" + uploadPath + File.separator);
    }

    // 获取文件的访问URL
    public static String getFileUrl(String filename) {
        if (filename == null || filename.isEmpty()) {
            return "";
        }
        // 拼接完整的URL，包含服务器地址
        return SERVER_URL + FILE_PREFIX + filename;
    }

    // 获取文件的完整路径
    public static String getFilePath(String filename) {
        if (filename == null || filename.isEmpty()) {
            return "";
        }
        return UPLOAD_PATH + filename;
    }
} 